<template>
  <a-modal :title="title" :width="600" :visible="visible" :confirmLoading="confirmLoading" @cancel="handleCancel">
    <template slot="footer">
      <a-popconfirm :title="$t('解绑后将不能再进行扫码登录，您确定要进行解绑吗？')" @confirm="()=>unBind()">
        <a-button type="primary" v-if="model.wxOpenId">{{ $t('解绑') }}</a-button>
      </a-popconfirm>
      <a-button type="primary" v-if="model.wxOpenId" @click="changeBind">{{ $t('换绑') }}</a-button>
      <a-button type="default" @click="handleCancel">{{ $t('关闭') }}</a-button>
    </template>
    <a-spin :spinning="confirmLoading">
      <div>
        <a-row style="margin-top: 10px">
          <a-col :span="6" style="text-align: right">{{ $t('用户账号') }}：</a-col>
          <a-col :span="18">{{ model.username }}</a-col>
        </a-row>
        <a-row style="margin-top: 10px">
          <a-col :span="6" style="text-align: right">{{ $t('用户姓名') }}：</a-col>
          <a-col :span="18">{{ model.realname }}</a-col>
        </a-row>
        <a-row v-show="!model.wxOpenId" style="margin-top: 10px">
          <a-col :span="6"></a-col>
          <a-col :span="18" style="color: orange">{{ tips }}</a-col>
        </a-row>
        <a-row v-show="!model.wxOpenId" style="margin-top: 30px; margin-bottom: 20px">
          <a-col :span="6"></a-col>
          <a-col :span="14" style="display: flex; justify-content: center; position: relative">
            <div id="qrcode" ref="qrcode" style="width: 100px; height: 100px"></div>
            <div
              v-if="isScan"
              style="
                width: 100px;
                height: 100px;
                position: absolute;
                left: 50%;
                margin-left: -50px;
                background-color: rgba(255, 255, 255, 0.9);
              "
            ></div>
            <div
              v-if="isScan"
              style="
                width: 100px;
                height: 100px;
                position: absolute;
                left: 50%;
                margin-left: -50px;
                display: flex;
                justify-content: center;
                align-items: center;
              "
            >
              <div>
                <a-icon type="check-circle" theme="filled" style="font-size: 60px; color: #00c900" />
                <div style="line-height: 1; margin-top: 10px">{{ $t('扫码成功') }}</div>
              </div>
            </div>
          </a-col>
        </a-row>
        <a-row v-show="model.wxOpenId" style="margin-top: 10px">
          <a-col :span="6" style="text-align: right">{{ $t('微信昵称') }}：</a-col>
          <a-col :span="18">{{ model.wxUsername }}</a-col>
        </a-row>
        <a-row v-show="model.wxOpenId" style="margin-top: 10px">
          <a-col :span="6" style="text-align: right">{{ $t('微信头像') }}：</a-col>
          <a-col :span="18">
            <img v-if="model.wxAvatar" :src="model.wxAvatar" style="width: 50px; height: 50px" />
          </a-col>
        </a-row>
      </div>
    </a-spin>
    <yarn-cert-out-captcha-modal ref="yarnModal" @ok="handleSubmitCallback" @cancel="handleSubmitClose"></yarn-cert-out-captcha-modal>
  </a-modal>
</template>

<script>
import QRCode from 'qrcodejs2'
import { getAction,postAction } from '@/api/manage'
import YarnCertOutCaptchaModal from '@/views/setting/modules/YarnCertOutCaptchaModal'
import {changePassword} from "@api/api";
export default {
  name: 'UserBindModal',
  components: {
    YarnCertOutCaptchaModal
  },
  data() {
    return {
      title: this.$t('账号绑定'),
      visible: false,
      model: {},
      confirmLoading: false,
      tips: '',
      isScan: false,
      lockReconnect: false
    }
  },
  created() {},
  methods: {
    edit(record) {
      this.model = Object.assign({}, record)
      this.isScan = false
      this.initWebSocket()
      if (this.model.wxOpenId) {
        this.tips = ''
      } else {
        this.tips = this.$t('请使用微信扫一扫扫码绑定')
        this.getQrcode(1)
      }
      this.visible = true
    },
    getQrcode(arg) {
      let query={
        merchant: sessionStorage.getItem('id')
      }
      if(arg!=undefined){
        query.scene='random=' + this.model.id+'&username='+this.model.username+'&ex=1'
      }else{
        query.scene='random=' + this.model.id+'&username='+this.model.username
      }
      getAction('/guest/system/authQrCodeImg', query).then((res) => {
        if (res.success) {
          document.getElementById('qrcode').innerHTML = '' //获取生成二维码后显示的容器的ID
          this.qrCode = new QRCode('qrcode', {
            width: 100, //二维码的宽度
            height: 100, //二维码的高度
            text: res.result, //调用weixincode()方法时后台传的code
            colorDark: '#000', //二维码颜色
            colorLight: '#fff', //二维码底色
            title: '',
          })
          this.qrCode._el.title = ''
        }
      })
    },

    changeBind() {
      this.isScan = false
      delete this.model.wxOpenId
      this.$nextTick(() => {
        this.$forceUpdate()
        this.tips = this.$t('请使用微信扫一扫扫码绑定')
        this.getQrcode(1)
      })
    },
    unBind(){
      let that=this;
      postAction('/system/unbindWxApp',{userId:that.model.id}).then(res=>{
        if(res.success){
          that.$message.success(res.message)
          that.$emit('ok')
          that.visible = false
          return
        } else if(res.code == 750){ // 需要验证码
          //认证
          that.$refs.yarnModal.show({userId:that.model.id});
          return
        }
        that.$message.error(res.message)
      })
    },
    handleSubmitClose(){
      let that=this;
      this.close();
    },
    handleSubmitCallback(formData){
      let that=this;
      postAction('/system/unbindWxApp',formData).then(res=>{
        if(res.success){
          that.$refs.yarnModal.close();

          this.$message.success(res.message)
          this.$emit('ok')
          this.visible = false
          return
        }
        this.$message.error(res.message)
      })
    },
    // 关闭
    handleCancel() {
      this.close()
    },
    close() {
      this.$emit('close')
      this.visible = false
    },
    initWebSocket: function () {
      // WebSocket与普通的请求所用协议有所不同，ws等同于http，wss等同于https
      var url = window._CONFIG['domianURL'].replace('https://', 'wss://').replace('http://', 'ws://') + 'websocket/' + this.model.id
      this.websock = new WebSocket(url)
      this.websock.onopen = this.websocketOnopen
      this.websock.onerror = this.websocketOnerror
      this.websock.onmessage = this.websocketOnmessage
      this.websock.onclose = this.websocketOnclose
    },
    websocketOnopen: function () {
      console.log('WebSocket连接成功')
      //心跳检测重置
      //this.heartCheck.reset().start();
    },
    websocketOnerror: function (e) {
      console.log('WebSocket连接发生错误')
      this.reconnect()
    },
    reconnect() {
      var that = this;
      if(that.lockReconnect) return;
      that.lockReconnect = true;
      //没连接上会一直重连，设置延迟避免请求过多
      setTimeout(function () {
        console.info("尝试重连...");
        that.initWebSocket();
        that.lockReconnect = false;
      }, 5000);
    },
    websocketOnmessage: function (e) {
      console.log('-----接收消息-------', e.data)
      var data = eval('(' + e.data + ')') //解析对象
      if (data.cmd == 'topic') {
        //扫码
        if (data.data.data.type == 'scan') {
          this.scan = '已扫码：' + data.data.data.topic
          this.isScan = true
          this.tips = this.$t('请在手机端进行绑定')
        }
        if (data.data.data.type == 'auth') {
          this.scan = '已授权：' + data.data.data.openId
          this.$message.success(this.$t('绑定成功'))
          this.$emit('ok')
          this.visible=false
        }
      }
      //心跳检测重置
      //this.heartCheck.reset().start();
    },
    websocketOnclose: function (e) {
      console.log('connection closed (' + e + ')')
      if (e) {
        console.log('connection closed (' + e.code + ')')
      }
      this.reconnect()
    },
    websocketSend(text) {
      // 数据发送
      try {
        this.websock.send(text)
      } catch (err) {
        console.log('send failed (' + err.code + ')')
      }
    },
  },
}
</script>